package com.sljy.hzk;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.sljy.hzk.animation.AnimationManager;
import com.sljy.hzk.base.UserInfo;
import com.sljy.hzk.entity.DangerDatabaseEntity;
import com.sljy.hzk.entity.MainNoticeNumEntity;
import com.sljy.hzk.entity.TaskBodyEntity;
import com.sljy.hzk.entity.TaskDatabaseEntity;
import com.sljy.hzk.net.BaseCallBack;
import com.sljy.hzk.net.CommonResult;
import com.sljy.hzk.net.HttpHeper;
import com.sljy.hzk.net.service.TaskService;
import com.sljy.hzk.net.service.UserServive;
import com.sljy.hzk.annotation.ActivityInfo;
import com.sljy.hzk.base.BaseActivity;
import com.sljy.hzk.entity.UserEntity;
import com.sljy.hzk.room.AppDataBase;
import com.sljy.hzk.room.dao.DangerDao;
import com.sljy.hzk.room.dao.TaskBodyDao;
import com.sljy.hzk.room.dao.TaskDao;
import com.sljy.hzk.room.dao.UserDao;
import com.sljy.hzk.ui.FixPswActivity;
import com.sljy.hzk.ui.LoginActivity;
import com.sljy.hzk.ui.PicHeadCutActivity;
import com.sljy.hzk.ui.QrCodeActivity;
import com.sljy.hzk.ui.detection.DetectionMainActivity;
import com.sljy.hzk.ui.exam.ExamLoadingActivity;
import com.sljy.hzk.ui.exam.ExamMainActivity;
import com.sljy.hzk.ui.task.Task_LodingActivity;
import com.sljy.hzk.util.TimeUtils;
import com.sljy.hzk.util.picture.FileUtils;
import com.sljy.hzk.util.picture.TakePictureUtils;
import com.sljy.hzk.view.CircleImageView;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.http.Url;
//import static com.sljy.hzk.R.id.settingFragment;

@ActivityInfo(layout = R.layout.activity_main, isShowActionBar = false)
public class MainActivity extends BaseActivity {
    @BindView(R.id.userName)
    TextView userName;
    @BindView(R.id.workName)
    TextView workName;
    @BindView(R.id.headBtn)
    CircleImageView headBtn;
    @BindView(R.id.taskBtn)
    ImageButton taskBtn;
    @BindView(R.id.peixunBtn)
    ImageButton peixunBtn;
    @BindView(R.id.weihaiyinshuBtn)
    ImageButton weihaiyinshuBtn;
    @BindView(R.id.changeUser)
    ImageView changeUser;
    @BindView(R.id.changePsw)
    ImageView changePsw;
    //    @BindView(R.id.exitUser)
//    ImageView exitUser;
    @BindView(R.id.setting_userName)
    TextView setting_userName;
    @BindView(R.id.setting_workName)
    TextView setting_workName;
    @BindView(R.id.setting_headBtn)
    CircleImageView setting_headBtn;
    @BindView(R.id.settingFragment)
    DrawerLayout settingFragment;
    @BindView(R.id.taskNum)
    ImageView taskNum;
    @BindView(R.id.examNum)
    ImageView examNum;
    public TakePictureUtils takePictureUtils;
    private String cachePath;
    UserEntity user;
    UserDao userDao;
    private Uri picPath;
    //user对应的权限集合
    List<Integer> menus;
    @Override
    protected void init() {
        cachePath = FileUtils.generateImgePath(this);
        user = UserInfo.getUserInfo();
        userDao = AppDataBase.getInstance().getUserDao();
        takePictureUtils = TakePictureUtils.Builder.from(this).isCompressor(false).isTailor(false).creat();
        takePictureUtils.setTakeCallBacklistener(new TakePictureUtils.TakePictureListener() {
            @Override public void successful(File outFile) {
                //Glide.with(PicHeadCutActivity.this).load(outFile).into(img);
                picPath = Uri.fromFile(new File(cachePath));
                Intent intent1 = new Intent("com.android.camera.action.CROP");
                intent1.setDataAndType(Uri.fromFile(outFile), "image/*");
                intent1.putExtra("crop", "true");
                //intent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));//
                intent1.putExtra(MediaStore.EXTRA_OUTPUT, picPath);
                intent1.putExtra("aspectX", 1);
                intent1.putExtra("aspectY", 1);
                intent1.putExtra("outputFormat", Bitmap.CompressFormat.JPEG);
                intent1.putExtra("outputX", 320);
                intent1.putExtra("outputY", 320);
                intent1.putExtra("scale", true);
                intent1.putExtra("scaleUpIfNeeded", true);
                intent1.putExtra("return-data", false);

                startActivityForResult(intent1, 1);
            }
            @Override public void failed(int errorCode, List<String> deniedPermissions) {
                Log.i("PicHeadCutActivity", "图片error");
            }
        });

        if (user != null) {
            String[] p =  user.getPosition().split("-");
            userName.setText(user.getName());
            workName.setText(p[2]);
            setting_userName.setText(user.getName());
            setting_workName.setText(p[2]);

            //根据权限开关闭功能
            List<Integer> menuList = user.getMenuList();
            for(Integer menu : menuList){
                switch (menu){
                    case 1:
                        taskBtn.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        peixunBtn.setVisibility(View.VISIBLE);
                        break;
                    case 3:
                        weihaiyinshuBtn.setVisibility(View.VISIBLE);
                        break;
                }
            }

            HttpHeper.get().create(UserServive.class)
                    .getIndex(user.getUserId(), user.getCpId())
                    .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                    .compose(getThread())
                    .subscribe(new BaseCallBack<MainNoticeNumEntity>() {
                        @Override
                        public void onCallBackSuccess(MainNoticeNumEntity data) {
                            //显示消息
                            List<Integer> menuList = user.getMenuList();
                            for(Integer menu : menuList){
                                switch (menu){
                                    case 1:
                                        taskNum.setVisibility(data.getTask() > 0 ? View.VISIBLE : View.GONE);
                                        break;
                                    case 2:
                                        examNum.setVisibility(data.getExam() > 0 ? View.VISIBLE : View.GONE);
                                        break;
                                }
                            }
                        }
                        @Override
                        public void onFail(String mes) {
                            showToast(mes);
                        }
                    });

            //加载头像
            if(!user.getHeadPic().equals("")){
                String imgPath = user.getHeadPic().replace("\\","/");
                Glide.with(this).load(imgPath).into(headBtn);
                Glide.with(this).load(imgPath).into(setting_headBtn);
            }

        }
        //头像
        headBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(DoEffect(v,event,false)){
                    settingFragment.openDrawer(Gravity.LEFT);
                }
                return false;
            }
        });
        //任务
        taskBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(DoEffect(v,event,false)){
                    startActivity(Task_LodingActivity.class);
                    //startActivity(QrCodeActivity.class);
                }
                return false;
            }
        });
        //培训
        peixunBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(DoEffect(v,event,false)){
                    startActivity(ExamLoadingActivity.class);
                }
                return false;
            }
        });
        //危害因素
        weihaiyinshuBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(DoEffect(v,event,false)){
                    startActivity(DetectionMainActivity.class);
                }
                return false;
            }
        });

        setting_headBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(DoEffect(v,event,false)){
                    showPhotoDialog();
                }
                return false;
            }
        });

        changeUser.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(DoEffect(v,event,true)){
                    UserEntity u = userDao.getPermanentUser();
                    if(u != null){
                        if(u.getUserId() == user.getUserId()){
                            u.setIsPermanent(0);
                            userDao.Update(u);
                        }
                    }
                    startActivity(LoginActivity.class);
                }
                return false;
            }
        });

        changePsw.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(DoEffect(v,event,true)){
                    settingFragment.closeDrawer(Gravity.LEFT);
                    startActivity(FixPswActivity.class);
                }
                return false;
            }
        });

        clearUnlineData();
    }

    private boolean DoEffect(View view, MotionEvent event, Boolean isToColor){
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                if(isToColor)
                    AnimationManager.Instance().DoColorAction(view, Color.GRAY);
                else
                    AnimationManager.Instance().DoScaleAction(view, 1.0f,1.05f,1.0f,1.05f,50);
                break;
            case  MotionEvent.ACTION_UP:
                if(isToColor)
                    AnimationManager.Instance().DoColorAction(view, Color.WHITE);
                else
                    AnimationManager.Instance().DoScaleAction(view, 1.05f,1.0f,1.05f,1.0f,50);
                return true;
        }
        return false;
    }

    private void showPhotoDialog() {
        new MaterialDialog.Builder(this)
                .items("选择本地照片", "拍照")
                .itemsCallback((dialog, itemView, position, text) -> {
                    switch (position) {
                        case 0: // 选择本地照片
                            takePictureUtils.getByAlbum();
                            break;
                        case 1: // 拍照
                            takePictureUtils.getByCarema();
                            break;
                    }
                }).show();
        //startActivity(PicHeadCutActivity.class);
    }

    /**
     * 清理离线数据
     * */
    private void clearUnlineData (){
        //清理本地已经过期的任务
        String date = TimeUtils.dateToStr(TimeUtils.getNowDate());
        AppDataBase roomData = AppDataBase.getInstance();
        TaskBodyDao body = roomData.getTaskBodyDao();
        for(TaskBodyEntity l : body.get()){
            if(TimeUtils.compare_date(date, l.getDate()) == 1){
                body.delete(l);
            }
        }
        DangerDao danger = roomData.getDangerDao();
        for(DangerDatabaseEntity l : danger.get()){
            if(TimeUtils.compare_date(date, l.getResultDate()) == 1){
                danger.delete(l);
            }
        }
        TaskDao task = roomData.getTaskDao();
        for(TaskDatabaseEntity l : task.getAll()){
            if(TimeUtils.compare_date(date, l.getResultDate()) == 1){
                task.delete(l);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1){
            //
            File file = null;
            try {
                file = new File(new URI(picPath.toString()));
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part requestImgPart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
            Call<CommonResult<String>> result = HttpHeper.get().create(UserServive.class).upHeadPicGetUrl(requestImgPart);
            result.enqueue( new Callback<CommonResult<String>>(){
                @Override
                public void onResponse(Call<CommonResult<String>> call, Response<CommonResult<String>> response) {
                    if(response.isSuccessful()){
                        Glide.with(MainActivity.this).load(picPath).into(setting_headBtn);
                        Glide.with(MainActivity.this).load(picPath).into(headBtn);
                        user.setHeadPic(response.body().getData());
                        Call<CommonResult<String>> pr = HttpHeper.get().create(UserServive.class).upHeadPicSave(user.getUserId(),response.body().getData());
                        pr.enqueue( new Callback<CommonResult<String>>(){
                            @Override
                            public void onResponse(Call<CommonResult<String>> call, Response<CommonResult<String>> response) {
                                UserEntity u = userDao.getPermanentUser();
                                if(u != null){
                                    if(u.getUserId() == user.getUserId()){
                                        u.setHeadPic(user.getHeadPic());
                                        userDao.Update(u);
                                    }
                                }
                                Log.i(TAG,"上传成功"+response.body().getData());
                            }

                            @Override
                            public void onFailure(Call<CommonResult<String>> call, Throwable t) {
                                Log.i(TAG,"上传失败");
                            }
                        });
                    }else {
                        Log.i(TAG,"上传失败");
                    }
                }
                @Override
                public void onFailure(Call<CommonResult<String>> call, Throwable t) {
                    Log.e(TAG,"上传失败");
                }
            });

            return;
        }
        takePictureUtils.attachToActivityForResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
